from django.core.validators import RegexValidator
from django.shortcuts import render, redirect, HttpResponse

# Create your views here.

from app01 import models
def depart_list(request):
    """ 部门列表 """
    # 去数据库中获取所有的部门列表
    # 返回值为querySet [对象,对象,对象]
    queryset = models.Department.objects.all();
    # 获取数据渲染页面并返回前端
    return render(request, 'depart_list.html', {'queryset':queryset})

def depart_add(request):
    if request.method == 'GET':
        return render(request, "depart_add.html")

    # 获取用户POST提交数据（deptname输入为空）
    deptname = request.POST.get('deptname')

    # 保存到数据库
    models.Department.objects.create(deptname=deptname)

    # 重定向到部门列表
    return redirect("/depart/list/")

def depart_delete(request):
    """"删除部门"""
    nid = request.GET.get("nid")
    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/depart/list/")

def depart_edit(request, nid):
    """"修改部门"""
    #根据nid,获取当前数据
    row_object = models.Department.objects.filter(id=nid).first()
    print(row_object.id, row_object.deptname)
    if request.method == 'GET':
        return render(request, 'depart_edit.html', {'row_object':row_object})
    # 获取部门名称 更新数据库
    deptname = request.POST.get('deptname')
    models.Department.objects.filter(id=nid).update(deptname=deptname)

    # 重定向回到部门列表
    return redirect("/depart/list/")

def user_list(request):
    queryset = models.UserInfo.objects.all();
    #for obj in queryset:
        #print(obj.id, obj.name, obj.amount, obj.create_time.strftime("%Y-%m-%d"),obj.gender,obj.get_gender_display())
        #print(obj.depart_id) # 获取数据库中存储的那个字段值
        #print(obj.depart.deptname) #根据id关联数据库中表中获取depart（deptartment）对象
    #return HttpResponse("查询成功")
    return render(request, "user_list.html", {'queryset':queryset})

def user_add(request):
    if request.method == 'GET':
        """ 添加用户 (原始方法) """
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'department_list': models.Department.objects.all(),
        }
        print(context)
        return render(request, "user_add.html", context)

    username = request.POST.get('name')
    password = request.POST.get('password')
    age = request.POST.get("age")
    amount = request.POST.get("amount")
    create_time = request.POST.get("create_time")
    gender_id = request.POST.get('gender_id')
    depart_id = request.POST.get('depart_id')

    models.UserInfo.objects.create(name=username,password=password,age=age,amount=amount,create_time=create_time,gender=gender_id,depart_id=depart_id)
    return redirect("/user/list/")


# ################### ModelForm 示例 #####################
from django import forms
class UserModelForm(forms.ModelForm):
    # 可以增加字符输入校验长度
    name = forms.CharField(max_length=20, label="用户名")
    class Meta:
        model = models.UserInfo
        fields = ['name','password', 'age','amount','depart','create_time','gender']
        # widgets = {
        #     'name': forms.TextInput(attrs={'class': 'form-control'}),
        #     'password': forms.PassworkInput(attrs={'class': 'form-control'}),
        # }

    #通过获取底层代码渲染样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        ## Django 用self.fields.items() 获取fields
        for name, field in self.base_fields.items():
            ##print(name, field)
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

def user_model_from_add(request):
    """ 添加用户 ModelFrom """
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, "user_model_form_add.html", {'form':form})

    # 用户提交POST提交数据，数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法 则保存数据
        #{'name': '张小黄', 'password': '123123', 'age': 18, 'amount': Decimal('50000'), 'depart': <Department: 销售部>, 'create_time': datetime.datetime(2024, 4, 22, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'gender': 0}
        #print(form.cleaned_data)
        #models.UserInfo.objects.create()
        form.save()
        return redirect("/user/list/")
    else:
        print(form.errors)
        # 校验失败 将错误信息返回到页面上
        return render(request, "user_model_form_add.html", {'form': form})

def user_edit(request, nid):
    # 根据id取出该条数据,赋值给ModelForm对象
    row_object = models.UserInfo.objects.filter(id=nid).first()
    print(row_object.id, row_object.name)
    if request.method == 'GET':
        form = UserModelForm(instance=row_object)
        return render(request,"user_edit.html", {'form':form})
    #POST请求添加修改过后的数据
    form = UserModelForm(instance=row_object, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request, "user_edit.html", {'form': form})

def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")

def pertty_list(request):
    queryset = models.PrettyNum.objects.all().order_by("level")
    return render(request, "pertty_list.html", {'queryset':queryset})

class PrettyNumAddModelForm(forms.ModelForm):
    # 验证：方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$',"手机号格式错误"),],
    )
    class Meta:
        model = models.PrettyNum
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.base_fields.items():
            print(name, field)
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

    # 验证：方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']
        print(txt_mobile)
        
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValueError("手机号已存在")

        if len(txt_mobile) != 11:
            #验证不通过
            raise ValueError("格式错误")

        #验证通过，用户输入的值返回
        return txt_mobile

class PrettyNumEditModelForm(forms.ModelForm):
    # 验证：方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$',"手机号格式错误"),],
    )
    class Meta:
        model = models.PrettyNum
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.base_fields.items():
            print(name, field)
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

    # 验证：方式2 钩子函数
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']
        print(txt_mobile)

        if len(txt_mobile) != 11:
            #验证不通过
            raise ValueError("格式错误")


        #验证通过，用户输入的值返回
        return txt_mobile



def pertty_add(request):
    if request.method == 'GET':
        form = PrettyNumAddModelForm()
        return render(request,"pertty_add.html", {'form':form})

    # POST提交号码数据
    form = PrettyNumAddModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pertty/list/")
    else:
        print(form.errors)
        # 校验失败 返回页面
        return render(request, "pertty_add.html", {'form': form})

def pertty_edit(request, nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyNumEditModelForm(instance=row_object)
        return render(request, "pertty_edit.html", {'form':form})

    form = PrettyNumEditModelForm(instance=row_object, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pertty/list/")
    else:
        print(form.errors)
        return render(request, "pertty_edit.html", {'form': form})

def pertty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pertty/list/")













